package cn.weixin.song.model;

import java.util.Date;
import java.util.List;

import cn.weixin.song.model.base.BaseCouponSn;

import com.google.common.collect.Lists;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.DateUtils;
import com.jcbase.core.util.RandomUtils;
import com.jcbase.core.view.InvokeResult;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class CouponSn extends BaseCouponSn<CouponSn> {
	public static final CouponSn dao = new CouponSn();
	public CouponSn addCouponSn(Integer uid, ActivityAward activityAward) {
		CouponSn couponSn=new CouponSn();
		couponSn.setUid(uid);
		couponSn.setCouponId(activityAward.getCouponId());
		couponSn.setActivityId(activityAward.getActivityId());
		couponSn.setReceiveTime(new Date());
		couponSn.setStartTime(activityAward.getStartDate());
		couponSn.setExpireTime(activityAward.getEndDate());
		couponSn.setStatus(0);
		couponSn.setSnCode(createSnCode());
		couponSn.save();
		return couponSn;
	}
	
	public String createSnCode(){
		return DateUtils.formatDateToUnixTimestamp(new Date())+RandomUtils.getRandomDigit(4);
	}
	
	public List<Record> getMyNotUseCouponSnList(Integer uid){
		String sql="select sn.*,s.name as shop_name,s.address,c.name as coupon_name,c.frequency_limit from coupon_sn sn left join coupon c on sn.coupon_id=c.id left join shop s on c.shop_id=s.id where sn.uid=? and sn.status=0 and sn.expire_time>=? order by sn.id desc";
		return Db.find(sql,uid,DateUtils.format(new Date(), "yyyy-MM-dd"));
	}
	
	public List<Record> getMyUsedCouponSnList(Integer uid){
		String sql="select sn.*,s.name as shop_name,s.address,c.name as coupon_name,c.frequency_limit from coupon_sn sn left join coupon c on sn.coupon_id=c.id left join shop s on c.shop_id=s.id where sn.uid=? and sn.status=1 order by sn.used_time desc";
		return Db.find(sql,uid);
	}

	public Record findBySnCode(String sn) {
		String sql="select sn.*,s.name as shop_name,s.address,c.name as coupon_name from coupon_sn sn left join coupon c on sn.coupon_id=c.id left join shop s on c.shop_id=s.id where sn.sn_code=?";
		return Db.findFirst(sql,sn);
	}

	public InvokeResult consume(String snCode, String pwd) {
		CouponSn couponSn=this.get(CommonUtils.getConditions(new Condition("sn_code",Operators.EQ,snCode)));
		if(couponSn==null){
			return InvokeResult.failure("该券不存在！");
		}
		if(couponSn.getStatus().equals(1)){
			return InvokeResult.failure("该券已消费过！");
		}
		String expireTimeStr=DateUtils.format(couponSn.getExpireTime(), "yyyy-MM-dd")+" 23:59:59";
		if(DateUtils.parseDate(expireTimeStr, "yyyy-MM-dd HH:mm:ss").before(new Date())){
			return InvokeResult.failure("该券已过期！");
		}
		Coupon coupon=Coupon.dao.findByIdLoadColumns(couponSn.getCouponId(), "frequency_limit");
		if(coupon.getFrequencyLimit()>0){//有使用频率限制
			Date lastUsedTime=this.findLastUsedCouponSn(couponSn.getUid(),couponSn.getCouponId());
			if(lastUsedTime!=null){
				Date nextUseTime=DateUtils.addDay(lastUsedTime, coupon.getFrequencyLimit());
				nextUseTime=DateUtils.parseDate(DateUtils.format(nextUseTime, "yyyy-MM-dd")+" 00:00:01", "yyyy-MM-dd HH:mm:ss");
				if(nextUseTime.after(new Date())){
					return InvokeResult.failure("该券"+coupon.getFrequencyLimit()+"天内只能使用一次！");
				}
			}
		}
		Activity activity=Activity.dao.get(CommonUtils.getConditions(new Condition("id",Operators.EQ,couponSn.getActivityId())), "exchage_pwd");
		if(!activity.getExchagePwd().equals(pwd)){
			return InvokeResult.failure("核销密码有误！");
		}
		couponSn.setStatus(1);
		couponSn.setUsedTime(new Date());
		couponSn.update();
		return InvokeResult.success();
	}

	public Date findLastUsedCouponSn(Integer uid,Integer couponId){
		CouponSn couponSn=this.findFirst("select used_time from coupon_sn where uid=? and coupon_id=? and status=1 order by used_time desc limit 0,1", uid,couponId);
		if(couponSn!=null){
			return couponSn.getUsedTime();
		}
		return null;
	}
	
	public Page<Record> getCouponSnPage(int page, int rows, Integer aid,String keyword,
			String orderbyStr) {
		String select="select sn.*,u.mobilephone,u.id as uid,u.nickname,c.name as coupon_name";
		StringBuffer sqlExceptSelect=new StringBuffer("from coupon_sn sn left join user u on sn.uid=u.id left join coupon c on sn.coupon_id=c.id where sn.activity_id=?");
		List<Object> paras=Lists.newArrayList();
		paras.add(aid);
		if(StrKit.notBlank(keyword)){
			sqlExceptSelect.append(" and (u.mobilephone like ? or u.nickname like ?)");
			paras.add("'%"+keyword+"%'");
			paras.add("'%"+keyword+"%'");
		}
		if(StrKit.notBlank(orderbyStr)){
			sqlExceptSelect.append(" "+orderbyStr);
		}
		return Db.paginate(page, rows, select, sqlExceptSelect.toString(), paras.toArray());
	}
}
